package com.basic.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.basic.backend.common.ErrorCode;
import com.basic.backend.exception.BusinessException;
import com.basic.backend.model.dto.articles.ArticleQueryRequest;
import com.basic.backend.model.dto.articles.ArticleUpdateRequest;
import com.basic.backend.model.entity.Articles;
import com.basic.backend.model.vo.ArticleVO;
import com.basic.backend.service.ArticlesService;
import com.basic.backend.mapper.ArticlesMapper;
import com.basic.backend.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


/**
* @author ASUS
* @description 针对表【articles】的数据库操作Service实现
* @createDate 2025-03-03 22:07:44
*/
@Service
public class ArticlesServiceImpl extends ServiceImpl<ArticlesMapper, Articles>
    implements ArticlesService{


    @Resource
    private UserService userService;

    @Override
    public String getAuthorName(Long articleId) {
        Articles article = this.getById(articleId);
        return userService.getUserVO(article.getUserId()).getUserName();
    }

    @Override
    public Integer getWordCount(Long articleId) {
        if (articleId != null) {
            Articles article = this.getById(articleId);
            return article.getContent().length();
        }
        return 0;
    }

    @Override
    public boolean  saveArticle(Articles article) {
        //检查是否为空
        if (article == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        //检查标题是否符合
        if (article.getTitle() == null || article.getTitle().length() > 100) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        //检查内容是否符合
        if (article.getContent() == null || article.getContent().length() > 10000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        //检查用户id是否为空
        if (article.getUserId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id为空");
        }
        article.setContent(article.getContent());
        article.setTitle(article.getTitle());
        return this.save(article);
    }


    @Override
    public Page<ArticleVO> getArticlePage(ArticleQueryRequest request) {
        // 基础查询条件
        QueryWrapper<Articles> wrapper = new QueryWrapper<>();

        // 精确查询
        if (request.getArticleId() != null) {
            wrapper.eq("articleId", request.getArticleId());
        }
        if (request.getUserId() != null) {
            wrapper.eq("userId", request.getUserId());
        }

        // 模糊查询
        if (StringUtils.isNotBlank(request.getTitle())) {
            wrapper.like("title", request.getTitle());
        }

        // 状态查询
        if (request.getStatusList() != null && !request.getStatusList().isEmpty()) {
            wrapper.in("status", request.getStatusList());
        }

        // 时间范围
        if (request.getCreateTimeRange() != null) {
            Date start = request.getCreateTimeRange().getStartTime();
            Date end = request.getCreateTimeRange().getEndTime();
            if (start != null && end != null) {
                wrapper.between("createdAt", start, end);
            }
        }

        // 分页和排序
        // 分页和排序
        Page<Articles> page = new Page<>(request.getCurrent(), request.getSize());
        String sortField = request.getSortField();
        String sortOrder = request.getSortOrder();

        if (StringUtils.isNotBlank(sortField)) {
            // 处理排序方向
            boolean isAsc = (sortOrder != null && sortOrder.equalsIgnoreCase("asc"));
            // 特殊处理：如果按时间排序且未指定方向，默认降序
            if ("createdAt".equalsIgnoreCase(sortField) && sortOrder == null) {
                isAsc = false;
            }
            wrapper.orderBy(true, isAsc, sortField);
        } else {
            // 默认按创建时间降序
            wrapper.orderByDesc("createdAt");
        }

        // 执行查询
        Page<Articles> articlePage = this.page(page, wrapper);

        // 转换为VO
        return (Page<ArticleVO>) articlePage.convert(article -> {
            ArticleVO vo = new ArticleVO();
            BeanUtils.copyProperties(article, vo);
            vo.setAuthor(userService.getUserVO(article.getUserId()));
            return vo;
        });
    }


    @Override
    public Boolean updateArticle(Long id, ArticleUpdateRequest request, Long currentUserId) {
        // 检查参数
        if (id == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (request.getTitle() == null || request.getTitle().length() > 100) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (request.getContent() == null || request.getContent().length() > 10000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        //传递的文章id查询出来
        Articles article = this.getById(id);
        article.setUserId(currentUserId);
        //是否存在
        if (article == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "文章不存在");
        }
        article.setTitle(request.getTitle());
        article.setContent(request.getContent());
        //插入更新数据
        if (article.getUserId().equals(currentUserId)) {
            BeanUtils.copyProperties(request, article);
            this.updateById(article);
            return true;
        }
        return false;
    }


}




